<template>
  <div class="tag-manager-container">
    <!-- 搜索条件卡片 -->
    <el-card class="search-card" shadow="hover">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto" class="search-form">
        <el-form-item label="标签名称" prop="tag_name">
          <el-input placeholder="请输入标签名称" v-model="queryParams.tag_name" clearable style="width: 180px"/>
        </el-form-item>

        <el-form-item label="是否显示" prop="is_show">
          <el-select placeholder="全部" clearable v-model="queryParams.is_show" style="width: 100px">
            <el-option label="全部" value=""/>
            <el-option label="显示" :value="1"/>
            <el-option label="不显示" :value="0"/>
          </el-select>
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="resetElement(queryFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域和数据表格卡片 -->
    <el-card class="table-card" shadow="hover">
      <div class="operation-header">
        <div class="operation-buttons">
          <el-button type="success" :icon="Plus" size="small" @click="addTag">添加标签</el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="delSelected">删除所选标签</el-button>
        </div>
        <div class="stats-info">
          共 <span class="highlight">{{ count }}</span> 条记录
        </div>
      </div>

      <!-- 数据展示表格 -->
      <el-table ref="elTableRef" :data="tableData" v-loading="loading" style="width: 100%" class="data-table">
        <!-- 复选框 -->
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column prop="tag_id" label="ID" width="120" align="center"/>
        <el-table-column label="标签名称" min-width="180" align="center">
          <template #default="scope">
            <el-popover effect="light" trigger="hover" placement="top" width="auto">
              <template #default>
                <div>名称: {{ scope.row.tag_name }}</div>
              </template>
              <template #reference>
                <el-tag class="tag-tag">{{ scope.row.tag_name }}</el-tag>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="显示状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.is_show ? 'success' : 'info'" class="status-tag">
              {{ row.is_show ? '显示' : '不显示' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" min-width="140" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button link type="primary" size="small" @click="editHandler(scope.row)">修改</el-button>
              <el-button link type="danger" size="small" @click="deleteHandler(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          background
          v-model:current-page="page"
          @current-change="handleQuery"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          layout="total, sizes, prev, pager, next, jumper"
          :total="count"
        />
      </div>
    </el-card>

    <!-- 添加标签的弹框 -->
    <el-dialog v-model="isShowAddDialog" title="添加标签" width="500px">
      <el-form ref="addFormRef" :rules="addRules" :model="formData" label-width="100px" class="dialog-form">
        <el-form-item label="标签名称" prop="tag_name">
          <el-input autocomplete="off" placeholder="请输入标签名称" v-model="formData.tag_name"/>
        </el-form-item>

        <el-form-item label="是否显示" prop="is_show">
          <el-switch v-model="formData.is_show" active-text="显示" inactive-text="隐藏"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetElement(addFormRef)">重置</el-button>
          <el-button @click="isShowAddDialog = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm(addFormRef)">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改标签的弹框 -->
    <el-dialog v-model="isShowEditDialog" title="修改标签" width="500px">
      <el-form ref="editFormRef" :rules="editRules" :model="editFormData" label-width="100px" class="dialog-form">
        <el-form-item label="标签名称" prop="tag_name">
          <el-input autocomplete="off" placeholder="请输入标签名称" v-model="editFormData.tag_name"/>
        </el-form-item>

        <el-form-item label="是否显示" prop="is_show">
          <el-switch v-model="editFormData.is_show" active-text="显示" inactive-text="隐藏"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeFrom">取消</el-button>
          <el-button type="primary" @click="submitEditForm(editFormRef)">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import TagAPI, { type TagInfo, type QueryTag, type TagPageData } from "@/api/system/tag.api";
import { Delete, Plus } from "@element-plus/icons-vue"
import {ElTable, FormInstance, FormRules} from 'element-plus';
import { ref, reactive, onMounted } from 'vue';

const page = ref(1)
const count = ref(0)
const pageSize = ref(5)
const tableData = ref<TagInfo[]>([])
const elTableRef = ref<InstanceType<typeof ElTable> | null>(null)
const isShowAddDialog = ref<boolean>(false)
const isShowEditDialog = ref<boolean>(false)
const addFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()
const queryFormRef = ref<FormInstance>()

// 初始新增表单数据
const formData = ref<TagInfo>({
  tag_name: '',
  is_show: true
})

// 初始修改表单数据
const editFormData = ref<TagInfo>({
  tag_id: 0,
  tag_name: '',
  is_show: true
})

const queryParams = ref<QueryTag>({
  page: 1,
  pageSize: 10,
  tag_name: '',
  is_show: ''
})

const loading = ref(false)

onMounted(() => {
  fetchGetTags()
})

// 添加表单验证规则
const addRules = reactive<FormRules<TagInfo>>({
  tag_name: [
    { required: true, message: '标签名不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '长度必须是2-20个字符', trigger: 'blur' },
  ]
})

// 编辑表单验证规则
const editRules = reactive<FormRules<TagInfo>>({
  tag_name: [
    { required: true, message: '标签名不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '长度必须是2-20个字符', trigger: 'blur' },
  ]
})

// 重置
const resetElement = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.resetFields();
  fetchGetTags()
}

// 新增提交表单
const submitAddForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          ...formData.value,
          is_show: formData.value.is_show ? 1 : 0
        }

        await TagAPI.createTag(submitData);
        ElMessage.success('添加标签成功');
        isShowAddDialog.value = false;
        fetchGetTags();
      } catch (error) {
        console.error('添加失败:', error);
        ElMessage.error('添加标签失败');
      }
    }
  })
}

// 添加标签弹出表单
const addTag = async () => {
  formData.value = {
    tag_name: '',
    is_show: true
  }

  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  isShowAddDialog.value = true;
}

// 获取表格数据
const fetchGetTags = async () => {
  loading.value = true
  try {
    queryParams.value.page = page.value;
    queryParams.value.pageSize = pageSize.value;

    const result = await TagAPI.getTagsInfo(queryParams.value);

    tableData.value = result.tags;
    count.value = result.count;
  } catch (err) {
    console.log('获取标签数据失败:', err)
  } finally {
    loading.value = false
  }
}

// 修改标签弹出表单
const editHandler = async (tag: TagInfo) => {
  editFormData.value = {
    tag_id: tag.tag_id!,
    tag_name: tag.tag_name,
    is_show: Boolean(tag.is_show)
  }
  isShowEditDialog.value = true
}

// 修改提交表单
const submitEditForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          ...editFormData.value,
          is_show: editFormData.value.is_show ? 1 : 0
        }

        await TagAPI.updateTag(submitData as TagInfo);
        ElMessage.success('更新标签成功');
        isShowEditDialog.value = false;
        fetchGetTags();
      } catch (error) {
        console.error('更新失败:', error);
        ElMessage.error('更新标签失败');
      }
    }
  })
}

// 关闭修改表单
const closeFrom = async () => {
  if (editFormRef.value) {
    editFormRef.value.resetFields();
  }
  isShowEditDialog.value = false
}

// 删除勾选的标签
const delSelected = async () => {
  if (!elTableRef.value) return
  const selectedRows = elTableRef.value.getSelectionRows()
  if (selectedRows.length === 0) {
    ElMessage.warning('至少选择一条数据')
    return
  }

  const ids = selectedRows
    .filter((item: TagInfo) => item.tag_id != null)
    .map((item: TagInfo) => item.tag_id)
    .join(',')

  try {
    await TagAPI.delBatchTags(ids);
    ElMessage.success('删除所选标签成功');
    fetchGetTags();
  } catch (error) {
    ElMessage.error('删除失败');
  }
}

// 删除触发事件
const deleteHandler = (row: TagInfo) => {
  ElMessageBox.confirm(
    `你确认删除"${row.tag_name}"吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
    if (row.tag_id != null) {
      await TagAPI.deleteTag(row.tag_id);
      ElMessage.success('删除成功');
      fetchGetTags();
    }
  }).catch(() => {
    ElMessage.info('取消删除');
  })
}

// 条件搜索
const handleQuery = async () => {
  loading.value = true
  try {

    queryParams.value.page = page.value;
    queryParams.value.pageSize = pageSize.value;

    console.log('aaaa' + JSON.stringify(queryParams.value))
    const result = await TagAPI.getTagsInfo(queryParams.value);

    tableData.value = result.tags;
    count.value = result.count;
  } catch (err) {
    console.log('获取标签数据失败:', err)
  } finally {
    loading.value = false
  }

  fetchGetTags()
}


// 每页显示数量变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchGetTags();
}
</script>

<style scoped>
.tag-manager-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.search-buttons {
  margin-left: auto;
}

.table-card {
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.operation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.stats-info {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.highlight {
  color: #409EFF;
  font-weight: bold;
  margin: 0 4px;
}

.data-table {
  margin: 15px 0;
  border-radius: 8px;
  overflow: hidden;
}

.data-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.tag-tag {
  cursor: pointer;
  font-weight: 500;
  background-color: #ecf5ff;
  border-color: #d9ecff;
  color: #409eff;
}

.status-tag {
  padding: 5px 10px;
  border-radius: 12px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.dialog-form {
  padding: 0 20px;
}

.dialog-form :deep(.el-form-item) {
  margin-bottom: 22px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding-top: 10px;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .search-buttons {
    margin-left: 0;
    width: 100%;
    justify-content: flex-end;
  }

  .operation-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .stats-info {
    margin-top: 10px;
  }
}

@media (max-width: 576px) {
  .tag-manager-container {
    padding: 15px;
  }

  .dialog-form {
    padding: 0 10px;
  }

  .pagination-container {
    overflow-x: auto;
  }
}
</style>
